var app = getApp();
Page({
    data:{
        siteroot : app.siteInfo.siteroot.replace('app/index.php', ''),uniacid: app.siteInfo.uniacid,
        inited : false,
        helplist : [],
		bgmusic : false,
		closebg : false,
		info : {},
        isneedauth : false,
		current : 0,
        prizelist : [],
        cardlist : [],
        levelstep : [],
        curentlevel : {},
        nodes : '',
        nowindex : -1,
        isshowtip : false,
        isshowaddress : false,
        address : '',
        name : '',
        tel : '',
        street : '',
        mess : '',
        allcard : [],
        allgoods : [],
        gettype : 0,
        showqr : false,
        useqr : '',
        qrtype : 'money',
    },
    onLoad:function(options){
        var self = this;

        if( options.scene ){
            var list = options.scene.split('_');
            options.id = list[0] ? list[0] : 0;
            options.zfid = list[1] ? list[1] : 0;
        }
        var id = options.id ? options.id : (options.scene ? options.scene : '');
        var zfid = options.zfid ? options.zfid : '';
        var shopid = options.shopid ? options.shopid : '';
        self.setData({
            options : options,
        })
        
        var postdata = {
            id:id,
            op:'info',
            zfid:zfid,
            nowindex : self.data.nowindex,
        };

        app.com.getLocation(self,function(loc){
            postdata.lat = loc.latitude;
            postdata.lng = loc.longitude;

            app.com.auth(function(user){
                app.com.http('kabao','POST',postdata,0,false,'','',function(res){
                    if (res.data && !res.data.errno) {

                        if(res.data.data.info.isnav != 1){
                            app.com.setBar(app,self,shopid);
                        }

                        self.setData({
                            inited : true,
                            params : res.data.data.params,
                            info : res.data.data.info,
                            sharedata : res.data.data.sharedata,
                            levelstep : res.data.data.levelstep ?  res.data.data.levelstep : [],
                            allgoods : res.data.data.allgoods ?  res.data.data.allgoods : false,
                            allcard : res.data.data.allcard ?  res.data.data.allcard : false,
                            isneedauth : res.data.data.params.isneedauth == 1 ? true : false,
                            name : res.data.data.info.username ? res.data.data.info.username : '',
                            tel : res.data.data.info.usertel ? res.data.data.info.usertel : '',
                            street : res.data.data.info.userstreet ? res.data.data.info.userstreet : '',
                            address : res.data.data.info.useraddress ? res.data.data.info.useraddress : '',
                            useqr : app.com.murl('img',{op:'usekabao',m:'zofui_sales'}),
                        },function(){

                            if( self.data.info.actindex >= 0 ){
                                self.setData({
                                    current : self.data.info.actindex,
                                    curentlevel : self.data.levelstep[self.data.info.actindex]
                                },function(){
                                    self.setactprize();
                                })
                            }else{
                                self.setactprize();
                            }

                        })
                        wx.setNavigationBarColor({
                            frontColor: '#ffffff',
                            backgroundColor: res.data.data.info.color,
                        });

                        setTimeout(function(){
                            
                            var octoparse = require('../resource/wxParse/html2json2.js');
                            var transData = octoparse.parse(res.data.data.info.content);                   
                            self.setData({
                                nodes : transData,
                            })
                            
                            wx.setNavigationBarTitle({
                                title:  res.data.data.info.name,
                            });
                        },5)

                    }else{
                        app.com.alert(res.data.message);
                    }
                });
            });
        })
        
    },
    onPullDownRefresh: function () {
        if( this.data.isdown ) return false;
        this.setData({
            isdown : true,
        });
        
        this.onLoad( this.data.options );
        this.setData({
            isdown : false,
        });
        // 关闭下拉刷新
        wx.stopPullDownRefresh();

    },
    onShareAppMessage : function(){
        var self = this;
        return {
            title: self.data.sharedata.title,
            path: self.data.sharedata.path,
            imageUrl : self.data.sharedata.img,
        }
    },
    onShareTimeline(){
        return {
            title: this.data.sharedata.title,
            query: this.data.sharedata.query,
            imageUrl : this.data.sharedata.img,
        }
    },
    joinactpost: function() {
        var self = this;
        
        var postdata = {
            gid:self.data.good.id,
            op:'join',
            name : self.data.userinfo.name,
            tel : self.data.userinfo.tel,
        };
        if( !postdata.name || postdata.name == '' ){
            app.com.toast('请填写姓名');return false;
        }
        if( !postdata.tel || postdata.tel == '' ){
            app.com.toast('请填写联系电话');return false;
        }
        if( !app.com.verify('mobile',postdata.tel) ){
            app.com.toast('请填写正确的联系电话');return false;
        }

        app.com.http('jizi','POST',postdata,0,true,'','',function(res){
            if (!res.data.errno && res.data) {
                if( res.data.data && res.data.data.font ){
                    self.setData({
                        showgeted : true,
                        showgetedstr : false,
                        getfont : res.data.data.font,
                    })
                    var font = self.data.good.font;
                    for (var i = 0; i < font.length; i++) {
                        if( font[i].font == res.data.data.font ){
                            self.setData({
                                ['good.font['+i+'].isact'] : 1,
                            })
                        }
                    }
                }
                self.setData({
                    showjoin : false,
                })

                self.onPullDownRefresh();
            }else{
                app.com.toast(res.data.message);
            }
        })
        self.subMess();
    },
    showdis(){
        var self = this;
        if(self.data.params.xcxmess && wx.requestSubscribeMessage){
            wx.requestSubscribeMessage({
                tmplIds : self.data.params.xcxmess,
                complete : function(){
                	if(self.data.info.usetype*1 == 1){
                		self.setData({
                			showqr : true,
                			qrtype : 'money',
                		})
                	}else{
                		self.selectComponent("#inputmoney").showfn();
                	}
                }
            })
        }else{
        	if(self.data.info.usetype*1 == 1){
        		self.setData({
        			showqr : true,
        			qrtype : 'money',
        		})
        	}else{
        		self.selectComponent("#inputmoney").showfn();
        	}
        }
    },
    subbindparent(e){
        var self = this;
        if(!e.detail){
            app.com.toast('请输入消费金额');
            self.selectComponent("#inputmoney").showfn();
            return false;
        }
        var postdata = {
            money: e.detail,
            op : 'dismoney',
            kabao : self.data.info.id,
        };
        app.com.confirm('提交后会立即减掉余额，确定消费吗？',function(){
            app.com.http('kabao','POST',postdata,0,true,'','',function(res){
                if (!res.data.errno) {
                    app.com.alert(res.data.message,function(){});
                    self.setData({
                        'info.lastmoney' : res.data.data.lastmoney
                    })
                    
                }else{
                    app.com.alert(res.data.message);
                    self.selectComponent("#inputmoney").showfn();
                }
            });
        })
    },
    showtimes(){
        var self = this;
        if(self.data.params.xcxmess && wx.requestSubscribeMessage){
            wx.requestSubscribeMessage({
                tmplIds : self.data.params.xcxmess,
                complete : function(){
                	if(self.data.info.usetype*1 == 1){
                		self.setData({
                			showqr : true,
                			qrtype : 'times',
                		})
                	}else{
                		self.selectComponent("#inputtimes").showfn(1);
                	}
                }
            })
        }else{
        	if(self.data.info.usetype*1 == 1){
        		self.setData({
        			showqr : true,
        			qrtype : 'times',
        		})
        	}else{
        		self.selectComponent("#inputtimes").showfn(1);
        	}
        }
    },
    hideqr(){
		this.setData({
			showqr : false,
		})
    },
    subbindtimes(e){
        var self = this;
        if(!e.detail){
            app.com.toast('请输入使用次数');
            self.selectComponent("#inputtimes").showfn();
            return false;
        }
        var postdata = {
            times: e.detail,
            op : 'distimes',
            kabao : self.data.info.id,
            pid : self.data.curentlevel.id,
        };
        app.com.confirm('提交后会立即减掉使用次数，确定使用吗？',function(){
            app.com.http('kabao','POST',postdata,0,true,'','',function(res){
                if (!res.data.errno) {
                    app.com.alert(res.data.message,function(){});
                    self.setData({
                        ['levelstep['+self.data.current+'].lasttimes'] : res.data.data.lasttimes,
                        'curentlevel.lasttimes' : res.data.data.lasttimes,
                    })
                    
                }else{
                    app.com.alert(res.data.message);
                    self.selectComponent("#inputtimes").showfn(e.detail);
                }
            });
        })
    },
    buyit(){
        var self = this;
        if(this.data.isneedauth){
            this.selectComponent('#authbtn').hideauth();
            return false;
        }
        if(self.data.params.xcxmess && wx.requestSubscribeMessage){
            wx.requestSubscribeMessage({
                tmplIds : self.data.params.xcxmess,
                complete : function(){
                    self.showaddress();
                }
            })
        }else{
            self.showaddress();
        }
    },
    shareit(){
        this.selectComponent('#share').onClose();
    },
    showtip(){
        this.setData({
            isshowtip : true,
        })
    },
    hidetip(){
        this.setData({
            isshowtip : false,
        })
    },
    confirmb(){
        if(this.data.info.know){
            this.showtip();
        }else{
            this.confirmbuy();
        }
    },
    selectarea(){
        this.selectComponent('#ausarea').show();
    },
    confirmbuy(){
        var self = this;
        var postdata = {
            op : 'buyit',
            kabao : self.data.info.id,
            pid : self.data.curentlevel.id,
            address : self.data.address ? self.data.address : '',
            name : self.data.name ? self.data.name : '',
            tel : self.data.tel ? self.data.tel : '',
            street : self.data.street ? self.data.street : '',
            mess : self.data.mess ? self.data.mess : '',
            gettype : self.data.gettype ? self.data.gettype : '',
        };
        
        app.com.http('kabao','POST',postdata,0,true,'','',function(res){
            if (res.data && !res.data.errno) {
                
                if( res.data.data.payed == 1 ){
                    app.com.toast('已开通','success',function(){

                        self.hidetip();
                        self.hideaddress();
                        self.onLoad( self.data.options );
                    });
                }else if(postdata.gettype == 1){ 
                    app.com.toast('已提交申请','success',function(){
                        self.hidetip();
                        self.hideaddress();
                    });
                }else{
                    wx.requestPayment({
                        'appId' : res.data.data.appId,
                        'timeStamp': res.data.data.timeStamp,
                        'nonceStr': res.data.data.nonceStr,
                        'package': res.data.data.package,
                        'signType': 'MD5',
                        'paySign': res.data.data.paySign,
                        'success': function (payres) {
                            if( payres.errMsg == 'requestPayment:ok' ){
                                app.com.toast('已开通','success',function(){
                                    self.hidetip();
                                    self.hideaddress();
                                    self.onLoad( self.data.options );
                                });
                            }
                        },
                        'fail': function (payres) {
                            console.log(payres);
                        }
                    });
                }

            }else{
                app.com.alert(res.data.message);
            }
        });
    },
    hideaddress(){
        this.setData({
            isshowaddress : false,
        })
    },
    showaddress(){
        this.setData({
            isshowaddress : true,
        })
    },
    authfn(){
        this.setData({
            isneedauth : false,
        });
        this.buyit();
    },
    bindRegionChange(e){
        var self = this;
        self.setData({
            address : e.detail.value[0] +','+e.detail.value[1] +','+e.detail.value[2]
        })
    },
    changeinput(e){
        var key = e.currentTarget.dataset.name;
        this.setData({
            [key] : e.detail.value
        })
    },
    cposter(){
        var self = this;
        app.com.http('jizi','POST',{op:'getposter',id:self.data.good.id,path:self.data.sharedata.path},0,true,'','',function(res){
            if (!res.data.errno && res.data ) {
                self.setData({
                    posterurl : res.data.data.url
                });
            }else{
                app.com.toast(res.data.message);
            }
        });
    },
    swiperChange(e){
        this.setData({
            current : e.detail.current,
            nowindex : e.detail.current,
            curentlevel : this.data.levelstep[e.detail.current]
        },function(){
            this.setactprize();
        })
    },
    setactprize(){
        var actid = this.data.curentlevel.id+'';
        var glist = [];
        var clist = [];

        for (var i = 0; i < this.data.allgoods.length; i++) {
            let item = this.data.allgoods[i];
            let isin = 0;
            if(!item || !item.levelid){
                isin = 1;
            }else{
                for (var j = 0; j < item.levelid.length; j++) {
                    if(item.levelid[j]+'' == actid){
                        isin = 1;
                    }
                }
            }
            if(isin == 1) glist.push(item);
        }
        for (var i = 0; i < this.data.allcard.length; i++) {
            let item = this.data.allcard[i];
            let isin = 0;
            if(!item || !item.levelid){
                isin = 1;
            }else{
                for (var j = 0; j < item.levelid.length; j++) {
                    if(item.levelid[j]+'' == actid){
                        isin = 1;
                    }
                }
            }
            if(isin == 1) clist.push(item);
        }

        this.setData({
            prizelist : glist,
            cardlist : clist,
        })
    },
    showjoin(){
        this.setData({
            showjoin : !this.data.showjoin,
        });
    },
    hidegeted : function(){
        this.setData({
            showgeted : false,
        });
    },
    name : function(e){
        this.setData({
            'userinfo.name' : e.detail.value,
        });
    },
    tel : function(e){
        this.setData({
            'userinfo.tel' : e.detail.value,
        });
    },
    tabpay(e){
        this.setData({
            gettype : e.currentTarget.dataset.type
        })
    },
    location : function( e ){
        app.com.location( e );
    },
    otherapp : function( e ){
        app.com.otherapp( e );
    },
    navigateto : function( e ){
        app.com.navigateto( e );
    },
    redirectto : function( e ){
        app.com.redirectto( e );
    },    
    callphone : function(e){
        app.com.callphone( e );
    },
    toweburl : function(e){
        app.com.toweburl( e );
    },
    showimages : function( e ){
        app.com.showimages( e );
    },
    footNavigate(e){
        var url = e.currentTarget.dataset.url;
        wx.switchTab({
          url: url
        })
    },
})